<?php

class Rights extends Zend_Db_Table
{
    protected $_name = 'groupauthority';
    
    public function checkExist($user_id,$authority_id)
    {
        $select = $this->getAdapter();
        $prepare = $select->query('
                SELECT count(*) as all_records 
                FROM rights 
                WHERE user_id="'.(int)$user_id.'"
                AND authority_id="'.(int)$authority_id.'"');
        $result = $prepare->fetchAll(Zend_Db::FETCH_ASSOC);
        return $result[0]['all_records'];
    }
    
    public function ClearLinks($user_id)
    {
        $select = $this->getAdapter();
        $prepare = $select->query('DELETE FROM rights 
                                   WHERE user_id="'.$user_id.'"');
    }
    
    public function AddRights($user_id,$authority_id)
    {
        $data = array(
                    'authority_id' => $authority_id,
                    'user_id' => $user_id);
        $this->insert($data);
    }
    
    public function CanDo($user_id,$controller,$action)
    {
        $select = $this->getAdapter();
        $q = 'SELECT count(authority.id) as all_records 
              FROM authority 
              INNER JOIN groupauthority on groupauthority.authority_id = authority.id
              INNER JOIN user on user.authgroup_id = groupauthority.authgroup_id
              WHERE authority.controller="'.$controller.'"
              AND authority.action="'.$action.'"
              AND user.id="'.$user_id.'"';
        //echo $q.'<br>'; exit();
        $prepare = $select->query($q);
        $result = $prepare->fetchAll(Zend_Db::FETCH_ASSOC);
        return $result[0]['all_records']>0;
    }
    
    public function CanSeeProject($user_id,$project_id)
    {
        $select = $this->getAdapter();
        $query = 'SELECT count(*) as all_records 
                FROM userprojectlinks
                WHERE userprojectlinks.user_id = "'.(int)$user_id.'" AND
                userprojectlinks.project_id = "'.(int)$project_id.'"';
        $prepare = $select->query($query);
        $result = $prepare->fetchAll(Zend_Db::FETCH_ASSOC);
        return $result[0]['all_records']>0;
    }
}